package com.kcyu.sfherp.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.kcyu.sfherp.config.TimestampConverter;
import com.kcyu.sfherp.dto.SeriesSaleStatisticDTO;
import com.kcyu.sfherp.entity.Chmx;
import com.kcyu.sfherp.entity.CustomHistoryPrice;
import com.kcyu.sfherp.entity.Good;
import com.kcyu.sfherp.entity.utilEntity.ExcelGoodSeries;
import com.kcyu.sfherp.entity.utilEntity.ExcelSeriesDetail;
import com.kcyu.sfherp.entity.utilEntity.SeriesSaleStatistic;
import com.kcyu.sfherp.mapper.ms.GoodMapper;
import com.kcyu.sfherp.service.ExcelService;
import com.kcyu.sfherp.service.GoodService;
import com.kcyu.sfherp.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@RestController
@Api(tags = "商品相关接口")
@RequestMapping("/goods")
@Slf4j
public class GoodController {

    @Autowired
    private GoodService goodService;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private ExcelService excelService;

    @GetMapping("/query/{spinfo}")
    @ApiOperation("查询商品信息")
    public Map<Object, Object> queryGoodsByName(@PathVariable String spinfo) {
        List<Good> goods = goodMapper.UnionQueryGoodsStock(spinfo);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", goods);
        map.put("length", goods.size());
        return map;
    }

    @GetMapping("/queryRecentlyPrice/{spbh}")
    public Map<Object, Object> queryRecentlyPriceByName(@PathVariable String spbh) {
        try {
            List<CustomHistoryPrice> historyPrices = goodService.queryRecentlyPriceByspbh(spbh);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("data", historyPrices);
            map.put("length", historyPrices.size());
            return map;
        } catch (Exception e) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("data", "链接数据库失败！请检查网络连接");
            return map;
        }

    }

    @PostMapping("/queryHistoryPrice")
    public Map<Object, Object> queryGoodsByName(@RequestBody Map info) {
        List<CustomHistoryPrice> prices = goodService.queryHistoryPrice((String) info.get("khname"), (String) info.get("spname"));
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", prices);
        map.put("length", prices.size());
        return map;
    }


    @PostMapping("/getGoodsSeries")
    public ResponseResult<Set<String>> getGoodsSeries() {
        return new ResponseResult<>(200, goodService.getSeriesSet());
    }

    @PostMapping("/getSeriesInfo/{goodSeries}")
    public ResponseResult<List<Good>> getSeriesInfo(@PathVariable String goodSeries) {
        return new ResponseResult<>(200, goodService.getSeriesInfo(goodSeries));
    }

    @PostMapping("/exportSeriesExcel/{goodSeries}")
    public void exportSeriesExcel(HttpServletResponse response, @PathVariable String goodSeries, @RequestBody List<String> columns) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName1 = goodSeries + "系列库存表";
        String fileName = URLEncoder.encode(fileName1, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<Good> seriesInfo = goodService.getSeriesInfo(goodSeries);

        WriteCellStyle headStyle = rewriteCellStyle();


        List<ExcelGoodSeries> excelGoodSeries = new ArrayList<>();
        for (Good good : seriesInfo) {
            ExcelGoodSeries excelGoodSeries1 = new ExcelGoodSeries();
            excelGoodSeries1.setSpbh(good.getSpbh());
            excelGoodSeries1.setSpname(good.getSpname());
            excelGoodSeries1.setK(good.getK());
            long v = Math.floorDiv(good.getKc().intValue(), (int) Math.ceil(Double.parseDouble(good.getK())));
            long mod = Math.floorMod(good.getKc().intValue(), (int) Math.ceil(Double.parseDouble(good.getK())));
            excelGoodSeries1.setJs(Long.valueOf(v).floatValue());
            excelGoodSeries1.setSs(Long.valueOf(mod).floatValue());
            WriteCellData<Number> numberWriteCellData = new WriteCellData<>();
            numberWriteCellData.setType(CellDataTypeEnum.NUMBER);
            numberWriteCellData.setNumberValue(BigDecimal.valueOf(good.getKcje()));
            excelGoodSeries1.setKcje(numberWriteCellData);
            excelGoodSeries1.setXl(good.getXl());

            excelGoodSeries.add(excelGoodSeries1);
        }

        log.info("导出系列库存, {}", excelGoodSeries);

        try {
            EasyExcel
                    .write(response.getOutputStream(), ExcelGoodSeries.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, headStyle))
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .includeColumnFieldNames(columns)
                    .sheet("sheet1")
                    .doWrite(excelGoodSeries);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }

    static WriteCellStyle rewriteCellStyle() {
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 10);
        headFont.setFontName("宋体");
        headStyle.setWriteFont(headFont);
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);

        return headStyle;
    }

    @PostMapping("/getSeriesOutStatistic")
    public ResponseResult<List<SeriesSaleStatistic>> getSeriesOutStatistic(@RequestBody SeriesSaleStatisticDTO dto) {
        return new ResponseResult<>(200, goodService.getSeriesSaleStatistic(dto.getSeriesName(), dto.getStartTime(), dto.getEndTime()));
    }

    @PostMapping("/getSeriesOutStatisticExcel")
    public void getSeriesOutStatisticExcel(HttpServletResponse response, @RequestBody SeriesSaleStatisticDTO dto) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName1 = dto.getSeriesName() + "系列出货统计表";
        String fileName = URLEncoder.encode(fileName1, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<SeriesSaleStatistic> seriesSaleStatistic = goodService.getSeriesSaleStatistic(dto.getSeriesName(), dto.getStartTime(), dto.getEndTime());

        WriteCellStyle headStyle = rewriteCellStyle();

        EasyExcel
                .write(response.getOutputStream(), SeriesSaleStatistic.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, headStyle))
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("sheet1")
                .doWrite(seriesSaleStatistic);
    }

    @PostMapping("/getSeriesOutDetail")
    public ResponseResult<List<Chmx>> getSeriesOutDetail(@RequestBody SeriesSaleStatisticDTO dto) {
        return new ResponseResult<>(200, goodService.getSeriesOutDetail(dto.getSeriesName(), dto.getStartTime(), dto.getEndTime()));
    }

    @PostMapping("/getSeriesOutDetailExcel")
    public void getSeriesOutDetailExcel(HttpServletResponse response, @RequestBody SeriesSaleStatisticDTO dto) throws IOException {
        List<Chmx> seriesOutDetail = goodService.getSeriesOutDetail(dto.getSeriesName(), dto.getStartTime(), dto.getEndTime());
        List<ExcelSeriesDetail> excelSeriesDetails = new ArrayList<>();
        for (Chmx chmx : seriesOutDetail) {
            ExcelSeriesDetail excelSeriesDetail = new ExcelSeriesDetail();
            excelSeriesDetail.setSpbh(chmx.getSpbh());
            excelSeriesDetail.setSpname(chmx.getSpname());
            excelSeriesDetail.setKhbh(chmx.getKhbh());
            excelSeriesDetail.setKhname(chmx.getKhname());
            excelSeriesDetail.setJs(chmx.getJs());
            excelSeriesDetail.setXs(chmx.getXs());
            excelSeriesDetail.setDw(chmx.getDw());
            excelSeriesDetail.setDw2(chmx.getDw2());
            excelSeriesDetail.setRq(chmx.getRq());
            excelSeriesDetails.add(excelSeriesDetail);
        }

        excelService.commonExportExcel(response, excelSeriesDetails, ExcelSeriesDetail.class, dto.getSeriesName() + "系列出货明细表");
    }

    @PostMapping("/getAlertGoods")
    public ResponseResult<List<Good>> getAlertGoods() {
        return new ResponseResult<>(200, goodService.getAlertGoods());
    }
}
